import os
from random import randint
from time import sleep

from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.common.by import By

import page
from base.base import Base
# from selenium.webdriver.common.action_chains import ActionChains
from appium.webdriver.common.touch_action import TouchAction

from tool.read_json import read_json
from tool.write_json import write_dict_to_json

cap = {
    "platformName": "Android",
    "platformVersion": "13",
    "deviceName": "HJS0218B27006432",
    "appPackage": "com.tencent.mm",
    "appActivity": "com.tencent.mm.ui.LauncherUI",
    # "recreateChromeDriverSessions": True
    "noReset": True,
    "chromedriverExecutable": r"D:\webdriver\chromedriver.exe",
    "newCommandTimeout": 6000,
    "fixImageTemplateScale": True,
    # "getMatchedImageResult": True,
    # 'imageMatchThreshold': 1
    # "unicodeKeyboard": True,
    # "resetKeyboard": True
}

driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", cap)
# driver.update_settings({"fixImageTemplateScale": True})
ff = Base(driver)
print(ff.driver.contexts)
driver.implicitly_wait(10)
size = ff.driver.get_window_size()
sleep(5)
ff.driver.swipe(size['width'] * 0.5, size['height'] * 0.4, size['width'] * 0.5, size['height'] * 0.9)
ff.driver.find_element(By.XPATH, '//*[contains(@text,"哈夫元宇宙x酒馆")]').click()
# input("等待")
print(ff.driver.contexts)
sleep(3)

ff.driver.switch_to.context('WEBVIEW_com.tencent.mm:appbrand0')

print(f"切换appbrand0的title{ff.driver.title}")

print(ff.driver.window_handles)

def click_test():
    global ff
    c = ff.base_find_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    print(c.location)
    print(c.size)
    ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    print(ff.base_get_element_attribute_value((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"),
                                              att='class'))
    ff.base_click_element((By.XPATH, '//*[contains(text(),"消息")]', ":pages/user/user.html:"))
    ff.base_click_element(
        (By.XPATH, '//*[contains(text(),"动态")]', ":pages/TUI-Conversation/conversation/conversation.html:"))
    ff.base_click_element((By.XPATH, '//*[contains(text(),"鱼塘")]', ":pages/dynamicPage/dynamicPage.html:"))
    ff.base_click_element((By.XPATH, '//*[contains(text(),"首页")]', ":pages/fishPond/fishPond.html:"))


def get_attr_test():
    global ff
    ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    print(ff.base_get_element_attribute_value((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"),
                                              att='class'))


def input_test():
    global ff
    ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    ff.base_click_element((By.CSS_SELECTOR, '.editIm', ":pages/user/user.html:"))
    input('手动滑一下')
    ff.base_click_element(
        (By.XPATH, '//*[contains(text(),"个性")]/../wx-view[2]', ':packageUser/pages/personalData/personalData.html:'))
    ff.base_input_value((By.CSS_SELECTOR, '.wx-xweb-textarea', ':packageUser/pages/personalData/personalData.html:'),
                        '4646546')
    sleep(2)
    ff.base_clear_value((By.CSS_SELECTOR, '.wx-xweb-textarea', ':packageUser/pages/personalData/personalData.html:'))
    sleep(2)
    ff.base_input_value((By.CSS_SELECTOR, '.wx-xweb-textarea', ':packageUser/pages/personalData/personalData.html:'),
                        '这是自我介绍')


def clear_test():
    global ff
    ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    ff.base_click_element((By.XPATH, '//*[contains(text(),"消息")]', ":pages/user/user.html:"))
    ff.base_click_element((By.CSS_SELECTOR, '.item-index--tui-conversation-item-name',
                           ":pages/TUI-Conversation/conversation/conversation.html:"))
    # ff.base_clear_value(
    #     (By.CSS_SELECTOR, '.input-index--TUI-message-input-area', ':packageMangHeIm/pages/TUI-Chat/chat.html:'))
    ff.base_input_value(
        (By.CSS_SELECTOR, '.input-index--TUI-message-input-area', ':packageMangHeIm/pages/TUI-Chat/chat.html:'),
        '123中国人')


def exist_test():
    global ff
    ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    print(ff.base_if_element_exist((By.XPATH, '//*[contains(text(),"消息")]', ":pages/user/user.html:")))


def url_test():
    global ff
    print(ff.base_get_current_page_url())
    ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    ff.base_click_element((By.XPATH, '//*[contains(text(),"消息")]', ":pages/user/user.html:"))
    print(ff.base_get_current_page_url())
    print(ff.base_get_current_activity())
    print(ff.base_get_current_package_name())


def text_test():
    global ff
    ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    ff.base_click_element((By.CSS_SELECTOR, '.editIm', ":pages/user/user.html:"))
    input('手动滑一下')
    print(ff.base_get_element_text(
        (By.XPATH, '//*[contains(text(),"个性")]/../wx-view[2]', ':packageUser/pages/personalData/personalData.html:')))


def screenshot_test():
    global ff
    module_name = str(os.path.basename(__file__)).split('.')[0]
    ff.base_get_screenshot_as_file(module_name)
    ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    ff.base_get_screenshot_as_file(module_name)
    ff.base_click_element((By.XPATH, '//*[contains(text(),"消息")]', ":pages/user/user.html:"))
    ff.base_get_screenshot_as_file(module_name)


def base_scroll_element_into_view_js():
    global ff
    offset_loc = By.CSS_SELECTOR, '.wx-swiper-slides', ':pages/home/home.html:'
    loc = By.XPATH, '//*[contains(text(),"长春")]', ':pages/home/home.html:'
    fp_chat_group = By.XPATH, '//*[text()="青年汇群"][2]', ':pages/home/home.html:'
    # el = ff.base_find_element(loc)
    # ff.base_scroll_element_into_view_js(loc, offset_loc=offset_loc)
    aa = By.XPATH, '/html/body/wx-scroll-view/div/div[1]/div/wx-view[3]/wx-view[2]/wx-waterfall/wx-view/wx-view[1]/wx-view[2]', ':pages/home/home.html:'
    input('等待')
    ff.base_scroll_element_into_view_js(loc, istop='false')
    ff.base_click_element(loc)
    ff.base_scroll_element_into_view_js(fp_chat_group, istop='false')
    # ff.base_up_to_down_windowscroll_js()


def base_up_to_down_windowscroll_js():
    global ff
    ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))
    ff.base_click_element((By.CSS_SELECTOR, '.editIm', ":pages/user/user.html:"))

    loc_area = By.XPATH, '/html/body', ':packageUser/pages/personalData/personalData.html:'
    loc = By.XPATH, '//*[contains(text(),"个性")]/../wx-view[2]', ':packageUser/pages/personalData/personalData.html:'
    # el1 = ff.base_find_element(loc_area)
    el2 = ff.base_find_element(loc)
    # driver.execute_script("arguments[0].scrollIntoView();", el2)
    # driver.execute_script("arguments[0].scrollIntoView(true);", el2)
    # driver.execute_script("arguments[0].scrollIntoView(false);", el2)
    # ff.driver.execute_script("window.scrollTo(0,0);")
    # print(ff.driver.get_window_size())
    # print(el2.location)
    # ff.base_up_to_down_windowscroll_js(loc, offset=100)
    aa = By.XPATH, '/html/body/wx-view[1]/wx-form/span/wx-view[2]/wx-view[1]/wx-view[1]', ':packageUser/pages/personalData/personalData.html:'
    ff.base_scroll_element_into_view_js(loc, istop='false', offset_loc=aa)
    ff.base_click_element(
        (By.XPATH, '//*[contains(text(),"个性")]/../wx-view[2]', ':packageUser/pages/personalData/personalData.html:'))
    ff.base_input_value((By.CSS_SELECTOR, '.wx-xweb-textarea', ':packageUser/pages/personalData/personalData.html:'),
                        '4646546')
    sleep(2)
    ff.base_clear_value((By.CSS_SELECTOR, '.wx-xweb-textarea', ':packageUser/pages/personalData/personalData.html:'))
    sleep(2)
    ff.base_input_value((By.CSS_SELECTOR, '.wx-xweb-textarea', ':packageUser/pages/personalData/personalData.html:'),
                        '这是自我介绍')


def another_test():
    ff.base_click_element(
        (By.XPATH, '/html/body/wx-scroll-view/div/div[1]/div/wx-view[1]/wx-view[3]/wx-view', ":pages/home/home.html:"))
    loc = (By.XPATH,
           '/html/body/wx-view/wx-list-components/wx-view/wx-view/wx-view[2]/wx-navigator[4]/wx-view/wx-view[2]/wx-view',
           ':packageHome/pages/shopHome/shopHome.html:')
    ff.base_scroll_element_into_view_js(loc)
    ff.base_click_element(loc)
    ff.driver.switch_to.context('NATIVE_APP')
    print(ff.driver.context)
    ff.base_click_element((By.ID, 'com.tencent.mm:id/be4'))


def native_test():
    global ff

    # input('切换原生app')
    # ff.driver.switch_to.context('NATIVE_APP')
    # ff.base_click_element((By.XPATH, '//android.widget.RelativeLayout[@content-desc="更多功能按钮"]/android.widget.ImageView'))
    # input('再次切换至webview')
    # ff.driver.switch_to.context('WEBVIEW_com.tencent.mm:appbrand0')
    # ActionChains(ff.driver).move_by_offset(1145, 202).click().perform()
    # TouchAction(ff.driver).tap(x=1155, y=200).perform()
    # input('操作')
    # TouchAction(ff.driver).tap(x=1077, y=2652).perform()
    # ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]', ":pages/home/home.html:"))

    # 基类，坐标点击验证
    # ff.base_native_click_location(x=1155, y=200)
    # ff.base_native_click_location(x=1077, y=2652)

    # 基类，opencv初始化验证
    # ff.base_opencv_init('img_50_template.png')
    # ff.base_click_element((AppiumBy.IMAGE, 'img_50_xcx.png')) # 缩放的50%元素图片

    # 基类，opencv验证
    # ff.base_click_element((AppiumBy.IMAGE, 'img_4.png'))

    # 基类，偏移量点击
    # ff.base_opencv_offset_click((AppiumBy.IMAGE, 'img_4.png'), offset_x=850, offset_y=700)

    # 基类，验证在小程序外部切回原生
    # click_test()
    # input('切回微信原生')
    # ff.base_click_element(
    #     (By.XPATH, '//android.widget.RelativeLayout[@content-desc="更多功能按钮"]/android.widget.ImageView'))



import base64
import cv2


def base64_convertor():
    img = cv2.imread("223.jpg")
    width, height = img.shape[1], img.shape[0]
    print(width, height)

    driver.switch_to.context('NATIVE_APP')
    encode = base64.b64encode(open("img_4.png", 'rb').read())
    print(driver.get_window_size())
    # print(encode, type(encode))
    # print(str(encode))
    # print(encode.decode())
    driver.update_settings({"defaultImageTemplateScale": driver.get_window_size()['width'] / width})
    print(driver.get_window_size()['width'] / width)
    el = driver.find_element(AppiumBy.IMAGE, encode.decode())
    print(el.size)
    print(el.location)
    print(el.rect)
    input('切换')
    ff.driver.switch_to.context('WEBVIEW_com.tencent.mm:appbrand0')
    el.click()
    print(el.size)
    print(el.location)
    print(el.rect)
    ff.base_get_screenshot_as_file('abc', el, 'assert')


def image_dingwei():
    global ff, driver
    # input('操作')
    # driver.find_element(AppiumBy.IMAGE, 'img.png')


def mark_area(x1, y1, x2, y2, filename, msg_en):
    img = cv2.imread("img_4.png")
    p1 = x1, y1
    p2 = x2, y2
    cv2.rectangle(img, p1, p2, (0, 255, 0), 2)
    a = '标记框'
    b = 0.666
    font = cv2.FONT_HERSHEY_SIMPLEX
    imgzi = cv2.putText(img, f"{a}:{b}", (x1, y1 - 15), font, 1, (0, 255, 255), 4)
    cv2.imwrite('77.jpg', img)

def find_elements():
    global ff
    print(ff.base_find_elements(page.chat_baping_theme_list))
    el_list = ff.base_find_elements(page.chat_baping_theme_list)
    time_list = ["10", "20", "30", "60", "120", "520"]
    case_num = 0
    case_dict = {}
    for i in el_list:
        sub_id = i.get_attribute("id")
        sub_loc = By.XPATH, f'//*[@id ="{sub_id}"]/wx-view/wx-view', page.chat_url
        sub_text = ff.base_get_element_text(sub_loc)
        index = randint(0, 5)
        time_loc = By.CSS_SELECTOR, f"#\\{index+30}", page.chat_url
        time = time_list[index]
        msg = f"这是测试 {sub_text} 的文案"
        case_dict.update(
            {
                f"case{case_num}": {
                    "sub_loc": sub_loc,
                    "sub_name": sub_text,
                    "time_loc": time_loc,
                    "time": time,
                    "msg": msg
                }
            }
        )
        case_num += 1
    print(case_dict)
    ff.base_find_element(('xpath', '//*[@id ="item0"]/wx-view/wx-view', ':packageMangHeIm/pages/TUI-Chat/chat.html:'))
    ff.base_find_elements(('css selector', '#\\30 ', ':packageMangHeIm/pages/TUI-Chat/chat.html:'))
    write_dict_to_json(case_dict,'baping_paras.json')
    print(read_json('baping_paras.json'))

if __name__ == '__main__':
    input("等")
    # find_elements()
    # clear_test()
    click_test()
    # base64_convertor()
    # mark_area(30, 30, 100, 100)
    # screenshot_test()
# input("等待")
#
# ff.base_click_element((By.XPATH, '//*[contains(text(),"我的")]'))
# ff.base_click_element((By.XPATH, '//*[contains(text(),"消息")]'))
# ff.base_click_element((By.XPATH, '//*[contains(text(),"动态")]'))
# ff.base_click_element((By.XPATH, '//*[contains(text(),"鱼塘")]'))
# ff.base_click_element((By.XPATH, '//*[contains(text(),"首页")]'))
# driver.find_element(By.XPATH, '/html/wx-tab-bar-wrapper/tab-bar/wx-view/wx-view[5]/wx-view[2]').click()
# 查看多个页面的句柄以及展示情况
# print(ff.driver.window_handles)
# print("当前句柄：" + ff.driver.current_window_handle)
# for window in ff.driver.window_handles:
#     ff.driver.switch_to.window(window)
#     # print("切换后句柄：" + driver.current_window_handle)
#     print(window+":"+ff.driver.title)


"""
['NATIVE_APP']
等待1
['NATIVE_APP', 'WEBVIEW_com.tencent.mm', 'WEBVIEW_com.tencent.mm:appbrand0']
['CDwindow-92FD7D3483488BE42D3CC800E7BB3237', 'CDwindow-B428447E12D02BBD92827D31D35264D3', 'CDwindow-5A2FF2508A957D12607F0ACD59000E67', 'CDwindow-B442A27762C60A2340E69E79B692D173']
当前句柄：CDwindow-B442A27762C60A2340E69E79B692D173
切换后句柄：CDwindow-92FD7D3483488BE42D3CC800E7BB3237

切换后句柄：CDwindow-B428447E12D02BBD92827D31D35264D3

切换后句柄：CDwindow-5A2FF2508A957D12607F0ACD59000E67
wxd4185d00bf7e08ac:pages/tabBar/index/index.html:VISIBLE
切换后句柄：CDwindow-B442A27762C60A2340E69E79B692D173
wxaf35009675aa0b2a:home/pages/index.html:INVISIBLE(PAUSED)
"""
